package web.servlet.zy5.register.servlet;

import org.apache.commons.beanutils.BeanUtils;
import web.servlet.zy5.register.dao.UserDao;
import web.servlet.zy5.register.dao.UserDaoImpl;
import web.servlet.zy5.register.domin.User;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author: 18148
 * @Date: 2020-05-30 15:46:41
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
     // Map<String, String[]> map = req.getParameterMap();
      //  User user=new User();
      //  try {
      //      BeanUtils.populate(user,map);
      //  } catch (IllegalAccessException e) {
      //      e.printStackTrace();
       // } catch (InvocationTargetException e) {
       //     e.printStackTrace();
       // }
        UserDao dao = new UserDaoImpl();
        User user = dao.selectByName(username);
        if (user == null) {
            int i = dao.register(username, password);
            if (i > 0) {
                req.setAttribute("username", username);
                req.getRequestDispatcher("/sServlet").forward(req, resp);
            }
        }else {
            req.setAttribute("register_error", "注册失败或用户名重复！");
            req.getRequestDispatcher("/fServlet").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
